<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import {
    useGetSnCodeInfoForOrderDetailUpdateSnCodeService,
    useOrderDetailGoodUpdateSnCodeService,
  } from '@/services/module/order/useDetail'
  import { ElMessageBox } from 'element-plus'
  import { PropType, ref, watch } from 'vue'
  import CreateCodeModal from '@/views/code/list/detail/components/createCodepopup/index.vue'
  import { cloneDeep } from 'lodash'

  const { updateForm, updateLoading, update, resetForm } = useOrderDetailGoodUpdateSnCodeService()
  const { snCodeInfo, getSnCodeInfoLoading, getSnCodeInfo } =
    useGetSnCodeInfoForOrderDetailUpdateSnCodeService()

  defineOptions({
    name: 'OrderDetailGoodUpdateModal',
  })

  const props = defineProps({
    good: {
      type: Object as PropType<OrderDetailAPIResponse.GoodListItem>,
      required: true,
    },
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 商品信息（内部使用）
  const _goodInfo = ref<OrderDetailAPIResponse.GoodListItem>({
    address: '',
    area: '',
    buyMarket: '',
    buyTime: '',
    city: '',
    codes: [],
    dl: null,
    endTime: '',
    fuselageImage: null,
    goodsBrand: '',
    goodsBrandId: '',
    goodsCode: '',
    goodsId: '',
    goodsModel: '',
    goodsName: '',
    goodsSpec: '',
    goodsSpecId: '',
    goodsType: '',
    id: '',
    isRelationRepair: 0,
    province: '',
    qty: 0,
    repairId: null,
    repairNo: null,
    snCodeImage: null,
    snCodeStatus: null,
    snCodeWarrantyType: null,
    specialBz: null,
    standard: null,
    town: '',
    userId: '',
    userName: '',
    userPhone: '',
    voltage: null,
    warrantyDay: null,
    xlh: null,
  })

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  // 序列号查询
  const querySnCode = ref('')

  // 创建序列号弹窗显示状态
  const createCodeModalVisible = ref(false)

  // 创建序列号弹窗实例
  const createCodeModalInstance = ref<InstanceType<typeof CreateCodeModal> | null>(null)

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    visible.value = false
    querySnCode.value = ''
    resetForm()
  }

  /**
   * 序列号查询事件
   */
  const onQuerySnCode = async () => {
    const errMsg = await getSnCodeInfo(querySnCode.value)
    if (errMsg) {
      ElMessageBox({
        title: '提示',
        type: 'warning',
        message: '查无此序列号，是否要去创建？',
        showCancelButton: true,
        beforeClose(action, instance, done) {
          if (action === 'confirm') {
            if (createCodeModalInstance.value) {
              createCodeModalInstance.value.setCode(querySnCode.value, {
                id: props.good.goodsId,
                specId: props.good.goodsSpecId,
                name: props.good.goodsName,
                specName: props.good.goodsSpec,
                code: props.good.goodsCode,
              })
            }
            createCodeModalVisible.value = true
            done()
            return
          }

          done()
        },
      })
      return
    }

    if (!snCodeInfo.value) {
      return
    }

    if (
      snCodeInfo.value.register &&
      snCodeInfo.value.register.userId !== props.orderDetail.userId
    ) {
      HMessageBox.error('两个序列号绑定的用户不一致，禁止更换')
      return
    }

    updateForm.value = {
      snCodes: [snCodeInfo.value.securityCode],
      workGoodsId: props.good.id,
    }
    Object.assign(_goodInfo.value, {
      address: snCodeInfo.value.register ? snCodeInfo.value.register.address : '',
      area: snCodeInfo.value.register ? snCodeInfo.value.register.area : '',
      buyTime: snCodeInfo.value.warrantyStartTime,
      city: snCodeInfo.value.register ? snCodeInfo.value.register.city : '',
      codes: [snCodeInfo.value.securityCode],
      endTime: snCodeInfo.value.warrantyEndTime,
      goodsBrand: snCodeInfo.value.zjProduct.brand,
      goodsBrandId: snCodeInfo.value.zjProduct.brandId,
      goodsId: snCodeInfo.value.id,
      goodsModel: snCodeInfo.value.zjProduct.model,
      goodsName: snCodeInfo.value.zjProduct.name,
      goodsSpec: snCodeInfo.value.spec.name,
      goodsSpecId: snCodeInfo.value.spec.id,
      province: snCodeInfo.value.register ? snCodeInfo.value.register.province : '',
      qty: 1,
      town: snCodeInfo.value.register ? snCodeInfo.value.register.town : '',
      userName: snCodeInfo.value.register ? snCodeInfo.value.register.name : '',
      userPhone: snCodeInfo.value.register ? snCodeInfo.value.register.phone : '',
      snCodeStatus: 1,
      goodsCode: snCodeInfo.value.zjProduct.itemNumber,
      saleModels: snCodeInfo.value.zjProduct.saleModels,
    })
  }

  /**
   * 保存修改点击事件
   */
  const onSaveClick = async () => {
    const res = await update(props.orderDetail.id)
    if (res) {
      if (res.code === 20000) {
        hideDialog()
        emits('update')
        HMessage.success('更新完成')
        return
      }

      HMessageBox.error(res.message)
      return
    }

    HMessageBox.error('更新失败，请稍后重试')
  }

  watch(visible, (value) => {
    if (value) {
      _goodInfo.value = cloneDeep(props.good)
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    title="修改设备信息"
    :width="600"
    unit="px"
    :loading="getSnCodeInfoLoading || updateLoading"
  >
    <el-form label-position="top" class="modal_form_content">
      <el-form-item label="新序列号查询">
        <div style="display: flex; width: 100%; column-gap: 12px">
          <el-input
            v-model.trim="querySnCode"
            placeholder="请输入序列号"
            @keyup.enter="onQuerySnCode"
          />
          <h-button type="primary" @click="onQuerySnCode">搜索</h-button>
        </div>
      </el-form-item>
      <el-form-item label="设备信息">
        <el-input
          readonly
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 16 }"
          :value="
            [
              _goodInfo.goodsCode || '',
              _goodInfo.goodsBrand || '',
              _goodInfo.goodsName || '',
              _goodInfo.goodsModel || '',
              _goodInfo.goodsSpec,
            ]
              .filter((o) => o)
              .join('  ')
          "
        />
      </el-form-item>
      <!-- <el-form-item label="系列号" class="mt10">
        <el-input readonly :value="_goodInfo.xlh" />
      </el-form-item> -->
      <el-form-item label="设备数量" class="mt10">
        <el-input readonly :value="_goodInfo.qty" />
      </el-form-item>
      <!-- <el-form-item label="电源电压（V）" class="mt10">
        <el-input readonly :value="_goodInfo.voltage" />
      </el-form-item>
      <el-form-item label="额定电流（V）" class="mt10">
        <el-input readonly :value="_goodInfo.dl" />
      </el-form-item>
      <el-form-item label="标准" class="mt10">
        <el-input readonly :value="_goodInfo.standard" />
      </el-form-item>
      <el-form-item label="特殊要求" class="mt10">
        <el-input readonly :value="_goodInfo.specialBz" />
      </el-form-item> -->
      <el-form-item label="购买时间" class="mt10">
        <el-input readonly :value="_goodInfo.buyTime" />
      </el-form-item>
      <el-form-item label="质保到期" class="mt10">
        <el-input readonly :value="_goodInfo.endTime" />
      </el-form-item>
      <el-form-item label="登记信息" class="mt10">
        <el-input
          :value="
            _goodInfo.userName
              ? _goodInfo.userName ||
                '' + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + _goodInfo.userPhone ||
                '' + '\r\n' + _goodInfo.province ||
                '' + '&nbsp;' + _goodInfo.city ||
                '' + '&nbsp;' + _goodInfo.area ||
                '' + '&nbsp; ' + _goodInfo.address ||
                ''
              : ''
          "
          readonly
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 16 }"
        />
      </el-form-item>
      <el-form-item label="合格证" class="mt10 sn-code">
        <el-input
          :model-value="
            _goodInfo.codes ? _goodInfo.codes.map((item) => item.securityCode).join('、') : ''
          "
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onSaveClick">保存修改</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>

    <CreateCodeModal
      ref="createCodeModalInstance"
      v-model="createCodeModalVisible"
      @update="onQuerySnCode"
    />
  </h-drawer>
</template>

<style scoped lang="scss">
  .modal_form_content {
    height: 100%;
    padding: 0 48px;
  }
</style>
